import React, { useState } from 'react';
import { Button } from 'antd';
import styles from './word.less';
import { Image } from 'antd-mobile';
import { CheckCircleOutlined, Modal, Popup, udp } from '@cscec/udp-mobile-ui';
import { Space } from 'antd-mobile/es/components/space/space';
import UnorderedListOutlined from '@ant-design/icons/lib/icons/UnorderedListOutlined';
import StarFill from 'antd-mobile-icons/es/StarFill';
import ExclamationCircleOutlined from '@ant-design/icons/lib/icons/ExclamationCircleOutlined';
import { Uphistory } from '@/pages/Schme/service';
import { updateScore } from '@/pages/Textbook/service';
import audioPlayer from '../../utils/audioPlayer';

const ImageWordSelection = ({ values, num, length, setNum, wordList }: any) => {
  const word = values.answer || values.name//正确答案
  // 所有单词弹窗
  const [modalvisible, setModalvisible] = useState(false)
  //控制弹窗 正确与错误
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  const [current, setCurrent] = useState(1)
  const [selectedWords, setSelectedWords] = useState<string | null>(null);
  //是否第一次选对
  const [isFirstTrue, setIsFirstTrue] = useState(true)

  const unitNum = wordList[0]?.unitIdEXName.substring(0, 1)
  // 单词数据
  const words = values.tbExerciseOptionVos.map((element) => {
    return element.name
  })
  // 图片URL
  const imageUrl = values.tbExerciseOptionVos[0]?.imgUrl
  //翻页功能
  const next = async () => {
    const result =  updateScore({
      unitId: values.unitId,
      type: 0,
      flag: isFirstTrue ? 0 : 1
    })
    if (num + 1 > length) {
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId: values.id,
        completionStatus: 2, studyFlag: 1, historyType: 1
      }).then((rt) => {
        udp.message('当前主题已经学习完毕!')
        udp.close()
      })
    } else {
      //翻页时，设置回true
      setIsFirstTrue(true)
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId: values.id,
        completionStatus: 2,
        studyFlag: 1, historyType: 1
      })
      setNum(num + 1)
    }
  }
  const mesArr = ['Great job!', 'Awesome!！', 'Wow, so clever!', 'Perfect!', 'High five!', 'Brilliant!', 'Way to go!', 'You’re amazing!', 'Keep up the good work!']
  const index = Math.floor(Math.random() * (8))
  const errorArr = ['Oops! Try again', 'Not yet.Try again!', 'Almost! Try once more', 'Another try!', 'Not right.Try again!', 'Keep going!']
  const errIndex = Math.floor(Math.random() * (6))

  // 继续按钮处理
  const handleContinue = () => {
    if (selectedWords) {
      if (selectedWords == word) {
        audioPlayer.playSuccess()
        setVisible(true)
      } else {
        audioPlayer.playFailure();//播放音效
        setIsFirstTrue(false)//这里设置不是第一次选对了
        setVisible1(true)
        //udp.alert('不正确！正确答案为'+`${word}`)
      }
    } else {
      udp.alert('请选择对应单词')
    }
  };

  const handleAllWord = () => {
    setModalvisible(true)
  }
  return (
    <>
      <div className={styles["word-header"]}>
        <div className={styles["word"]}>单词{num}/{length}</div>
        <div className={styles["word"]} onClick={handleAllWord}>
          <UnorderedListOutlined />
          所有单词
        </div>

      </div>
      <div className={styles["word-selection-game"]}>
        {/* 图片区域 */}
        <div className={styles["image-section"]}>
          <div className={styles["image-container"]}>
            <img
              src={imageUrl}
              alt="题目图片"
              className={styles["question-image"]}
            />

          </div>
        </div>
        {/* 选项区域 */}
        <div className={styles["options-section"]}>
          <Space direction="vertical" block>
            {words.map((option, index) => {
              return (
                <Button
                  key={index}
                  className={selectedWords == option ? styles["option-btn-selected"] : styles["option-btn"]}
                  block
                  onClick={() => {
                    setSelectedWords(option)
                  }}
                >
                  {option}
                </Button>
              );
            })}
          </Space>
        </div>
        <div className={styles["actions"]}>
          <Button
            size="large"
            onClick={handleContinue}
            className={styles["continue-button"]}
            block
          >
            Check
          </Button>
        </div>
      </div>
      <Popup
        visible={visible}
        bodyStyle={{
          height: '35vh',
          backgroundColor: '#ffffff',
          borderRadius: '25px 25px 0 0',
          textAlign: 'center',
        }}
      >
        <div
          style={{
            height: '180px',
            color: '#4caf50',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <CheckCircleOutlined
            style={{
              color: '#4caf50',
              fontSize: 'xxx-large',
              display: 'block'
            }} />
          {mesArr[index]}</div>

        <Button
          size="large"
          onClick={() => {
            setVisible(false)
            next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            backgroundColor: '#4caf50',
            color: '#ffffff'
          }}
          //disabled={!selectedImage}
          block
        >
          Next
        </Button>
      </Popup>
      <Popup
        visible={visible1}
        bodyStyle={{
          height: '35vh',
          background: '#ffffff',
          textAlign: 'center',
          borderRadius: '25px 25px 0 0'
        }}
      >
        <div
          style={{
            height: '180px',
            color: 'red',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <ExclamationCircleOutlined style={{
            color: 'red',
            fontSize: 'xxx-large',
            display: 'block'
          }} />
          {errorArr[errIndex]}</div>
        <Button
          size="large"
          onClick={() => {
            setVisible1(false)
            //setSelectedImage(null)
            //next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            color: '#ffffff',
            backgroundColor: '#f44336'
          }}
          //disabled={!selectedImage}
          block
        >
          Try Again
        </Button>
      </Popup>
      {/* 所有单词弹窗 */}
      <Modal visible={modalvisible}
        bodyClassName={styles["list-modal"]}
        content={
          <div className={styles["list-content"]}>
            <h3 className={styles['list-title']}>{`Unit ${unitNum}：所有单词`}</h3>
            <p className={styles['header-title']}>点击单词直接跳转学习</p>
            <div className={styles["word-list"]}>
              {wordList.map((item, index) => {
                return <div className={current === index + 1 ? styles["word-item-current"] : styles["word-item"]}
                  onClick={() => {
                    setCurrent(index + 1)
                    setNum(index + 1)
                    setModalvisible(false)
                  }}>
                  {item.type == 2 ? <span>{item.name}</span> : <Image
                    src={item.imgUrl}
                    height='21px'
                    fit='contain'
                  />}
                  <StarFill className={current === index + 1 ? styles["word-inco-current"] : styles["word-inco"]} />
                </div>
              })}
            </div>
            <Button className={styles["close-button"]}
              onClick={() => {
                setModalvisible(false)
              }}>关闭</Button>
          </div >
        }

        closeOnAction
        closeOnMaskClick={true}
        onClose={() => {
          setModalvisible(false)
        }}
      >

      </Modal >
    </>
  );
};

export default ImageWordSelection;